/**
 * 项目历史模型
 *
 * Created by snowingsea on 2020/05/09.
 */
const mongoose = require('mongoose');
const ProjectHistory = require('./mongo/project-history');
const Filter = require('./mongo/filter');
const { eventHub, eventKind } = require('./event-hub');

/**
 * 项目历史状态
 * @type {Object}
 */
const historyKind = {
  createVersion: 1, // 创建版本
  deleteVersion: 2, // 删除版本
  renameVersion: 3, // 版本更名
};

/**
 * 获取项目历史json信息
 * @param {ProjectHistory} projectHistory 项目历史信息
 * @return {Object}
 */
function getJson(projectHistory) {
  const historyId = projectHistory._id; // eslint-disable-line no-underscore-dangle
  return {
    historyId,
    projectId: projectHistory.projectId,
    kind: projectHistory.kind,
    createAt: historyId.getTimestamp().getTime(),
    details: projectHistory.details,
  };
}

/**
 * 获取项目历史信息
 * @param {String} historyId 项目历史id
 * @return {Promise}
 */
function getHistory(historyId) {
  return ProjectHistory.findOne({ _id: mongoose.Types.ObjectId(historyId) });
}

/**
 * 项目历史数目
 * @param {Object} options 用户筛选项
 * @return {Promise}
 */
function getCount(options = {}) {
  return ProjectHistory.countDocuments(options);
}

/**
 * 筛选历史列表
 * @param {Object} pagination 分页信息
 * @param {Object} options 用户筛选项
 * @return {Promise}
 */
function filter(pagination = {}, options = {}) {
  const { sortBy } = pagination;
  if (!sortBy || (sortBy === 'historyId') || (sortBy === 'createAt')) {
    pagination.sortBy = '_id';
  }
  return Filter.filter(ProjectHistory, pagination, options);
}

/**
 * 添加历史信息
 * @param {String} projectId 项目id
 * @param {Number} kind 历史类型
 * @param {Object} details 详细信息
 * @return {Promise}
 */
function addHistory(projectId, kind, details) {
  const history = new ProjectHistory({
    projectId: mongoose.Types.ObjectId(projectId),
    kind,
    details,
  });
  return history.save();
}

eventHub.on(eventKind.EVENT_PROJECT_REMOVE, (projectId) => ProjectHistory.deleteMany({ projectId: mongoose.Types.ObjectId(projectId) }));

/**
 * Export model definition object.
 */
module.exports = {
  kind: historyKind,

  getJson,

  getHistory,
  filter,
  getCount,

  addHistory,
};
